package com.itheima.reggie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.Common.BaseContext;
import com.itheima.reggie.Common.R;
import com.itheima.reggie.Service.OrderDetailService;
import com.itheima.reggie.Service.OrderService;
import com.itheima.reggie.Service.ShoppingCartService;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }


    /**
     * 后端订单的分页查询操作
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page<Orders>> page(int page, int pageSize, Long number, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime){

        log.info("查询订单明细");
        //构造分页构造器
        Page<Orders> pageInfo = new Page<>(page,pageSize);

        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(number!=null,Orders::getId,number);

        //queryWrapper.le（）——小于等于
        //queryWrapper.gt（）——大于
        //queryWrapper.ge（）——大于等于

        queryWrapper.ge(beginTime!=null,Orders::getOrderTime,beginTime);

        queryWrapper.le(endTime!=null,Orders::getCheckoutTime,endTime);
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        orderService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 订单更新操作
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders orders){
        log.info("订单操作Orders：+{}",orders);

        //更新状态
        orderService.updateById(orders);

        return R.success("订单更新成功");
    }

    /**
     * 用户最近订单查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage( int page, int pageSize ){
        //分页构造器对象
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> pageDto = new Page<>(page,pageSize);
        //构造查询条件对象
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //这里是直接把当前用户的分页全部结果查出来，要填加用户的id作为查询条件，否则会查询到其他的用户的订单
        queryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId());

        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo,queryWrapper);

        //通过OrderId查询相应的OrderDetail
        LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();

        //对orderDto的属性进行赋值
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map((item)->{
            OrdersDto ordersDto = new OrdersDto();
            //此时的orderDto对象里面OrderDetails属性是空值，下面进行赋值
            Long OrderId = item.getId();//获取订单的id
            List<OrderDetail> orderDetailList = orderDetailService.getOrderDetailByOrderId(OrderId);
            BeanUtils.copyProperties(item,ordersDto);
            //使用orderDto进行OrderDetails属性的赋值
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());

        //使用dto分页查询
        BeanUtils.copyProperties(pageInfo,pageDto,"records");
        pageDto.setRecords(ordersDtoList);

        return R.success(pageDto);
    }


    /**
     * 前端用户点击再来一单重复之前的订单到购物车中
     * 先清空再加到购物车中
     * @param map
     * @return
     */
    @PostMapping("/again")
    public R<String> againSubmit(@RequestBody Map<String,String> map){
        String ids = map.get("id");

        Long id =  Long.parseLong(ids);

        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        //获取订单对应的所有订单明细
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

        //通过用户的id把原来的购物车进行清空，使用clean方法
        shoppingCartService.clean();

        //获取用的id
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item)->{
            //把从order表中和order_details表中获取的数据赋值给购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if(dishId!=null){
                //如果菜品就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
            }else {
                //如果是套餐添加套餐的查询条件
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;

        }).collect(Collectors.toList());


        //把携带的数据的购物车批量插入购物车表 这
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("操作成功");
    }


}
